<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>商品购买</title>
  <link rel="stylesheet" type="text/css" href="./font-awesome.min.css">
  <link rel="stylesheet" type="text/css" href="./index.css">
  <script type="text/javascript" src="./vue.min.js"></script>
  <script type="text/javascript" src="./jstools.js"></script>
  <!-- <script type="text/javascript" src="./vconsole.min.js"></script>
  <script>
    // VConsole 默认会挂载到 `window.VConsole` 上
    var vConsole = new window.VConsole();
  </script> -->
</head>

<body>
  <div id="app" v-cloak>
    <div class="row-flex goods">
      <div class="row-flex-prefix goods-photo">
        <img :src="goodsInfo.photo" alt="商品照片">
      </div>
      <div class="row-flex-main goods-info">
        <div class="goods-title">{{goodsInfo.title}}</div>
        <div class="goods-subtitle">{{goodsInfo.subtitle}}</div>
        <div class="goods-status" v-if="goodsInfo.buyStatus !=='BUY'">
          <i class="fa fa-lock"></i> 未解锁
        </div>
      </div>
    </div>
    <div v-if="goodsInfo.buyStatus==='BUY'" class="panel-paid text-center">
      <div class="fa fa-unlock text-success"></div>
      <p>本册图书的资源及功能已解锁</p>
      <p>有效期至：{{goodsInfo.validDate}}</p>
    </div>
    <div v-else>
      <div class="pay-warning">
        <div class="pay-warning-label text-ellipsis">
          <i class="fa fa-star"></i> 购买后可解锁本册图书的所有资源及功能
          <div class="pay-warning-bg"></div>
        </div>
      </div>
      <div class="pay-selector">
        <div v-for="v in payOptionList" :key="v.id"
          :class="['row-flex', 'pay-option', {active: v.id === payOptionActive.id}]"
          :style="{width: v.width}"
          @click="payOptionChange(v)"
          align="center"
        >
          <div class="row-flex-main">{{v.label}}</div>
          <div class="row-flex-suffix text-danger">{{v.value}}</div>
        </div>
      </div>
      <div class="pay-button text-center" @click="paySubmit()">立即支付</div>
    </div>
    <div v-if="toastVisible" class="toast">{{toastMessage}}</div>
    <div v-if="modalVisible" class="modal-wrapper">
      <div class="modal text-center">
        <div class="modal-head">提示</div>
        <div class="modal-body">{{modalMessage}}</div>
        <div class="modal-foot">
          <div class="modal-button" @click="modalVisible = false">我知道了</div>
        </div>
      </div>
    </div>
  </div>
  <script>
    const _baseUrl = 'https://jsxf-gateway-qa.qalb.jsxfedu.net';
    const _appid = 'wx4b3373c2b5753cf7';
    let vm = new Vue({
      el: '#app',
      data: {
        orderId: '',
        goodsId: '',
        pickupCode: '',
        wxCode: '',
        goodsInfoRaw: {},
        goodsInfo: {photo: '', title: '', subtitle: '', buyStatus: ''},
        payOptionList: [
          {label: '体验15天', value: '1.0', width: '100%', id: '1'},
          {label: '30天', value: '6.0', width: '32%', id: '2'},
          {label: '90天', value: '12.0', width: '32%', id: '3'},
          {label: '180天', value: '28.0', width: '32%', id: '4'},
        ],
        payOptionActive: {},
        payTerminal: '',
        payType: 'alipay', // 支付方式: 'wechat', 'alipay'
        token: '',
        toastVisible: false,
        toastMessage: '',
        modalVisible: false,
        modalMessage: '',
      },
      mounted() {
        let urlParams = getUrlParams();
        this.token = urlParams.token || localStorage.getItem('token') || '';
        this.orderId = urlParams.orderid || '';
        this.goodsId = urlParams.goodsid || '';
        this.pickupCode = urlParams.sharecode || '';
        this.wxCode = urlParams.code || '';
        this.payTerminal = getTerminalType();
        // this.payType = urlParams.paytype || 'alipay';
        this.payType = getBrowserType();
        this.payType = (this.payType === 'wechat' ? 'wechat' : 'alipay');
        localStorage.setItem('token', this.token);
        if (this.payType === 'wechat' && !this.wxCode) {
          this.getWechatCode();
        } else {
          this.getGoodsInfo();
        }
        if (this.orderId) {
          this.getPrepayment({orderId: this.orderId});
        }
      },
      methods: {
        getGoodsInfo() {
          // this.goodsInfo = {photo: '', title: '小学英语 北师大版', subtitle: '三年级上册', buyStatus: 'NOT_BUY'};
          if (!this.pickupCode) return;
          let _this = this;
          let xhr = new XMLHttpRequest();
          xhr.withCredentials = true;
          xhr.addEventListener('readystatechange', function() {
            if(this.readyState === 4) {
              let res = jsonParse(this.responseText);
              if (res.code === 0 && res.data) {
                _this.goodsInfoRaw = res.data || {};
                let priceList = _this.goodsInfoRaw.priceList || [];
                _this.payOptionList = priceList.map(function (v, i) {
                  return {
                    id: v.id,
                    label: v.title,
                    value: (v.payAmount / 100 || 0).toFixed(2),
                    width: v.title.includes('体验') ? '100%' : '32%'
                  }
                });
                _this.goodsInfo = {
                  photo: _this.goodsInfoRaw.coverImgUrl || '',
                  title: (_this.goodsInfoRaw.studySectionName || '') + (_this.goodsInfoRaw.subjectName || '') + ' ' + (_this.goodsInfoRaw.textbookVersionName || ''),
                  subtitle: _this.goodsInfoRaw.textbookVolumesName || '',
                  validDate: _this.goodsInfoRaw.validDate || '',
                  buyStatus: _this.goodsInfoRaw.buyStatus || 'NOT_BUY'
                }
              } else {
                _this.$toast(res.msg || '获取商品信息失败');
              }
            }
          });
          xhr.open('GET', _baseUrl + '/jsxf-szjc/order/share-details?shareCode=' + _this.pickupCode);
          xhr.setRequestHeader('token', this.token);
          xhr.send();
        }, // 获取商品信息
        payOptionChange(item) {
          this.payOptionActive = item || {};
        }, // 选择商品规格
        paySubmit() {
          if (this.payOptionActive.id) {
            this.createOrder();
          } else {
            this.modalMessage = '请选择商品规格';
            this.modalVisible = true;
          }
        }, // 提交支付
        createOrder() {
          let _this = this;
          let url = _baseUrl + '/jsxf-szjc/order/create-share-book';
          let params = {
            goodsId: this.goodsId,
            goodsPriceId: this.payOptionActive.id,
            shareCode: this.pickupCode,
            wxCode: this.wxCode
          }
          let data = JSON.stringify(params);
          let xhr = new XMLHttpRequest();
          xhr.withCredentials = true;
          xhr.addEventListener('readystatechange', function() {
            if (this.readyState === 4) {
              let res = jsonParse(this.responseText);
              if (res.code === 0 && res.data) {
                _this.getPrepayment(res.data);
              } else {
                _this.modalMessage = '创建订单失败，请刷新页面后重试';
                _this.modalVisible = true;
              }
            }
          });
          xhr.open('POST', url);
          xhr.setRequestHeader('token', this.token);
          xhr.setRequestHeader('Content-Type', 'application/json');
          xhr.send(data);
        }, // 创建订单
        getPrepayment(orderInfo) {
          orderInfo = orderInfo || {};
          let _this = this;
          let url = _baseUrl + '/jsxf-szjc/order/mark-order';
          let returnUrl = window.location.href.split('?')[0] + '?goodsid=' + this.goodsId + '&sharecode=' + this.pickupCode;
          let params = {
            orderId: orderInfo.orderId,
            payType: this.payType === 'wechat' ? 'WEIXIN_JSAPI_PAY' : 'ALIPAY_WAP',
            returnUrl: returnUrl,
          }
          let data = JSON.stringify(params);
          let xhr = new XMLHttpRequest();
          xhr.withCredentials = true;
          xhr.addEventListener('readystatechange', function() {
            if (this.readyState === 4) {
              let res = jsonParse(this.responseText);
              if (res.code === 0 && res.data) {
                if (_this.payType === 'wechat') {
                  _this.wechatPay(res.data);
                } else {
                  _this.aliPay(res.data);
                }
              } else {
                _this.modalMessage = '获取预支付信息失败，请刷新页面后重试';
                _this.modalVisible = true;
              }
            }
          });
          xhr.open('POST', url);
          xhr.setRequestHeader('token', this.token);
          xhr.setRequestHeader('Content-Type', 'application/json');
          xhr.send(data);
        }, // 获取预支付信息
        aliPay(data) {
          let div = document.createElement('div');
          div.innerHTML = data;
          document.body.appendChild(div);
          document.forms[0].submit();
        }, // 支付宝支付
        wechatPay(data) {
          if (typeof window.WeixinJSBridge === 'undefined') {
            this.modalMessage = '请使用微信浏览器访问';
            this.modalVisible = true;
            return;
          }
          let _this = this;
          window.WeixinJSBridge.invoke('getBrandWCPayRequest', {
            appId: data.appId || _appid, // 优先使用后端返回的appId
            timeStamp: data.timeStamp || '', // 使用后端返回的timeStamp
            nonceStr: data.nonceStr || '', // 随机串
            package: data.package || '',
            signType: data.signType || 'MD5', // 微信签名方式
            paySign: data.paySign || '', // 微信签名
          }, function(res) {
            if (res.err_msg === "get_brand_wcpay_request:ok") {
              // 支付成功
              // 使用以上方式判断前端返回,微信团队郑重提示：
              // res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠，商户需进一步调用后端查单确认支付结果。
            } else if (res.err_msg === "get_brand_wcpay_request:cancel") {
              // 用户取消支付
            } else {
              // 支付失败
              console.log('支付失败: ' + res.err_msg);
            }
            let _url = window.location.href.split('?')[0];
            window.location.href = _url + '?token=' + _this.token + '&goodsid=' + _this.goodsId + '&sharecode=' + _this.pickupCode;
          });
        }, // 微信支付
        getWechatCode() {
          let appid = _appid;
          let redirect_uri = encodeURIComponent(window.location.href);
          let scope = 'snsapi_base'; // snsapi_base(静默授权) 或 snsapi_userinfo(弹出授权页面)
          // 跳转到微信授权页
          window.location.href = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' + appid + '&redirect_uri=' + redirect_uri + '&response_type=code&scope=' + scope;
        }, // 获取微信code
        $toast(message) {
          let _this = this;
          this.toastMessage = message || '';
          this.toastVisible = true;
          setTimeout(function () {
            _this.toastVisible = false;
          }, 3000);
        }, // 显示提示信息
      }
    });
  </script>
</body>

</html>
